<template>
  <div>
    <el-form ref="ruleForm" v-loading="loading" :model="blog" label-width="100px">
      <el-form-item label="博客标题" prop="blogTitle">
        <el-input v-model="blog.blogTitle" />
      </el-form-item>
      <el-form-item label="封面" prop="blogImage">
        <!--      <el-input v-model="blog.blogImage" />-->
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :headers="headers"
          :show-file-list="false"
          :on-success="handleUploadSuccess"
        >
          <img v-if="blog.blogImage" :src="blog.blogImage" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item label="分类名称" prop="typeName">
        <el-select v-model="blog.blogType" filterable clearable placeholder="请选择分类" style="width: 100%">
          <el-option
            v-for="item in typeList"
            :key="item.typeId"
            :label="item.typeName"
            :value="item.typeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标签" prop="tagIds">
        <el-select v-model="blog.tagIds" multiple placeholder="请选择标签" style="width: 100%" @focus="getEnabledTags">
          <el-option
            v-for="item in tagList"
            :key="item.tagId"
            :label="item.tagName"
            :value="item.tagId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="博客内容" prop="typeName">
        <!--      <el-input v-model="blog.blogContent" />-->
        <mavon-editor
          ref="md"
          v-model="blog.blogContent"
          :ishljs="true"
          style="min-height: 400px"
          code-style="idea"
          @change="change"
          @imgAdd="imgAdd"
          @imgDel="imgDel"
        />
      </el-form-item>
      <el-form-item label="来源" prop="blogSource">
        <el-select v-model="blog.blogSource" filterable placeholder="请选择来源" style="width: 100%">
          <el-option
            :key="1"
            :label="'原创'"
            :value="'原创'"
          />
          <el-option
            :key="2"
            :label="'转载'"
            :value="'转载'"
          />
          <el-option
            :key="3"
            :label="'翻译'"
            :value="'翻译'"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="博客简介" prop="blogRemark">
        <el-input v-model="blog.blogRemark" type="textarea" />
      </el-form-item>
      <el-form-item label="提交" label-width="100px">
        <el-button type="primary" @click="submitForm">提交</el-button>
      </el-form-item>
    </el-form>
  </div>

</template>

<script>
import blogApi from '../../../api/blog'
import { getToken } from '@/utils/auth'
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import tagApi from '../../../api/tag'
export default {
  name: 'BlogUpdate',
  components: {
    mavonEditor
  },
  data() {
    return {
      typeList: this.$store.getters.typeList,
      imageUrl: '',
      tagIds: [],
      tagList: [],
      headers: {
        Authorization: getToken()
      },
      uploadUrl: process.env.VUE_APP_UPLOAD_URL,
      loading: true,
      content: '', // 输入的markdown
      html: '', // 及时转的html
      imgFile: [],
      blog: {
        blogTitle: '',
        blogImage: null,
        blogContent: '',
        blogType: '',
        blogRemark: null,
        blogSource: ''
      }
    }
  },
  created() {
    this.getEnabledTags()
    if (this.$route.params.id) {
      this.loading = true
      blogApi.get(this.$route.params.id).then(res => {
        if (res.code === 200) {
          this.blog = res.data
          this.$message.success('已获取当前博客信息')
          this.loading = false
        } else {
          this.$message.error('获取当前博客信息失败')
          this.loading = false
        }
      }).catch(e => {
        this.loading = false
        this.$router.push('/Article/blog')
      })
    } else {
      this.loading = false
    }
  },
  methods: {
    handleUploadSuccess(res, file) {
      this.imageUrl = res.data
      this.blog.blogImage = res.data
    },
    getUploadUrl() {
      return process.env.VUE_APP_UPLOAD_URL
    },
    /**
     * 添加图片事件
     */
    imgAdd(pos, $file) {
      const formdata = new FormData()
      formdata.append('file', $file)
      this.imgFile[pos] = $file
      blogApi.uploadImg(formdata).then(res => {
        if (res.data.code === 200) {
          this.$message.success('上传成功')
          const url = res.data.data
          let name = $file.name
          if (name.includes('-')) {
            name = name.replace(/-/g, '')
          }
          const content = this.form.content
          // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)  这里是必须要有的
          if (content.includes(name)) {
            const oStr = `(${pos})`
            const nStr = `(${url})`
            const index = content.indexOf(oStr)
            const str = content.replace(oStr, '')
            const insertStr = (soure, start, newStr) => {
              return soure.slice(0, start) + newStr + soure.slice(start)
            }
            this.form.content = insertStr(str, index, nStr)
          }
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    // 触发图片删除的东西
    imgDel(pos) {
      delete this.imgFile[pos]
    },
    // 所有操作都会被解析重新渲染
    change(value, render) {
      // render 为 markdown 解析后的结果[html]
      this.html = render
    },
    submitForm() {
      this.loading = true
      blogApi.update(this.blog).then(res => {
        if (res.code === 200) {
          this.loading = false
          this.$message.success(res.msg)
          this.$router.push('/Article/blog')
        } else {
          this.loading = false
        }
      }, err => {
        this.$message.error(err)
        this.loading = false
      })
    },
    backBlog() {
      this.$router.push('/Article/blog')
    },
    getEnabledTags() {
      tagApi.getEnabledTags().then(res => {
        if (res.code === 200) {
          this.tagList = res.data
        }
      })
    }
  }
}
</script>

<style scoped>
  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    min-height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    min-height: 178px;
    display: block;
  }
</style>
